<?php

namespace App\Jobs;

use App\Models\Refund as RefundModel;
use App\Models\RefundDetail as RefundDetailModel;
use App\Services\PosApi\AliPayRefund;
use App\Services\PosApi\BankCardRefund;
use App\Services\PosApi\Order;
use App\Services\PosApi\ShouqianbaRefund;
use App\Services\PosApi\WxPayRefund;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

use App\Services\PosApi\RefundConfirm;
use Illuminate\Support\Facades\Log;

class RefundQueryJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    
    public $tries = 5;

    protected $refundDetail;

    protected $refundClass = [
        'shouqianba' => ShouqianbaRefund::class,
        'ali_pay' => AliPayRefund::class,
        'wx_pay' => WxPayRefund::class,
        'bank_card' => BankCardRefund::class
    ];


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($refundDetail)
    {
        $this->onConnection('redis-enhanced');
        $this->refundDetail = $refundDetail;
    }

    /**
     * Execute the job.
     * 收钱吧退款请求任务
     * @return void
     */
    public function handle()
    {
        $refundDetail = RefundDetailModel::find($this->refundDetail['id']);
        if ($refundDetail->status !== 1) {
            $sqbService = new $this->refundClass[$refundDetail->refund_platform];
            $result = $sqbService->query(['refund_no' => $refundDetail->refund_no], ['store_sn' => $this->refundDetail['store_sn']]);
            if ($result) {
                $refundDetail->status = 1;
                $refundDetail->trade_no = $result['order_sn'];
                $tenders = [];
                foreach ($result['tenders'] as $tender){
                    $tenders[] = [
                        'original_tender_sn'=>$tender['original_tender_sn'],
                        'amount'=>abs($tender['amount']),
                    ];
                }
                if($tenders){
                    $refundDetail->tenders = json_encode($tenders);
                }

                $refundDetail->save();

                $refund = (new RefundModel())->updateRefundStatus($refundDetail->refunds_id);

                //通知后端
                if($refund->status===1){
                    $rcService = new RefundConfirm();
                    $rcService->handle($refund);
                }
            } else {
                if($this->attempts()<5) { //失败后 不用在失败队列表里
                    $this->release(5);
                }
            }
        }

    }
}
